#include "CGameMario.h"

#include "Resource.h"
using namespace std;

#define KEY_DOWN(vk_code) ((GetAsyncKeyState(vk_code) & 0x8000)? 1: 0)

CGameMario::CGameMario(HINSTANCE hInstance, LPCSTR GameName, LPSTR lpCmdLine, int nShowCmd, int FPS, int ScreenWidth, int ScreenHeight)
	:CGame(hInstance, GameName, lpCmdLine, nShowCmd, FPS, ScreenWidth, ScreenHeight)
{
	quadtree = new QuadTree();
	 
}

CGameMario::~CGameMario(void)
{
	//delete mario;
	//mario.release();
	delete load_QTree;
	delete quadtree;
	delete camera;
}

void CGameMario::ProcessMenu(int Action)
{
	
}

void CGameMario::GameUpdate()
{
	update(_DeltaTime);
}

void CGameMario::RenderFrame()
{
	ResourceMng::GetInst(_directX->GetDevice(), _directX->GetBackBuffer())->GetSurface(L"..\\Resources\\Images\\imgBgGame.png")->Draw(NULL, NULL ); //chu y ham Draw co 2 tham so NULL
	
	_spriteHandler->Begin(D3DXSPRITE_ALPHABLEND);

	_mario->render(camera->getCamera().left, camera->getCamera().top);


	Object *obj;
	list<Object*>::iterator i;
	for (i = obj_list.begin(); i != obj_list.end(); i++)
	{
		obj = *i;
		obj->render(camera->getCamera().left, camera->getCamera().top);
	}

	_spriteHandler->End();
}

void CGameMario::LoadResource()
{
	HRESULT res = D3DXCreateSprite(_directX->GetDevice(), &_spriteHandler);


	camera = new Camera();

	load_QTree = new LoadMap(_directX->GetDevice(), _directX->GetBackBuffer(), _spriteHandler);
	load_QTree->loadFileObj("..\\Resources\\Map\\map.txt");
	load_QTree->loadFileToMap("..\\Resources\\Map\\map.txtquadtree.txt");
	load_QTree->deserialize(quadtree);

	//_mario = new Mario(_directX->GetDevice(), _directX->GetBackBuffer(), _spriteHandler, 200, 500, MS_NORMAL);
}
 

void CGameMario::update(float time)
{
	Object* obj;
	list<Object*>::iterator i;
	for (i = obj_list.begin(); i != obj_list.end(); i++)
	{
		obj = *i;
		//neu obj k ton tai
		//xoa obj tu quadtree
	}
	obj_list.clear();


	RECT rect_camera = camera->getCamera();
	quadtree->getObjFromCamara(rect_camera, &obj_list);


	for (i = obj_list.begin(); i != obj_list.end(); i++)
	{
		obj = *i;
		obj->update(&obj_list, p_input, time);
	}


	_mario->update(&obj_list, p_input, time);
	camera->update(_mario->getPosition());
}
 